import random
import string
from django.shortcuts import render
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from . import models


@login_required
def play(request):
    return render(request, 'game/play.html', {})


def init_level(level, fresh=False):
    if not level.word or fresh:
        word = models.Word.objects.order_by('?')[0]
        level.word = word
        level.save()
    choices = list(level.word.english.upper())
    for i in range(24 - len(choices)):
        choices.append(random.choice(string.ascii_uppercase))
    random.shuffle(choices)
    data = {
        'level': level.id,
        'score': level.score,
        'lives': level.lives,
        'word': level.word.english.upper(),
        'chinese': level.word.chinese,
        'choices': choices
    }
    return data


def get_level(request):
    try:
        level = request.user.level_set.filter(lives__gt=0).latest('id')
    except:
        level = models.Level.objects.create(user=request.user, lives=10)
        level.ip = request.META.get('REMOTE_ADDR', '0.0.0.0')
        level.save()
    return JsonResponse(init_level(level))


def finish(request):
    level_id = int(request.GET.get('level'), 0)
    lives = int(request.GET.get('lives'), 0)
    level = models.Level.objects.get(user=request.user, id=level_id)
    level.lives = lives
    if lives > 0:
        level.score += 1
        level.save()
        return JsonResponse(init_level(level, True))
    else:
        level.save()
        player = level.user.player
        player.times += 1
        if level.score > player.hi_score:
            player.hi_score = level.score
        player.save()
        return JsonResponse({})
